Skip to content

Fix stale aligned field merge in PriorityMergeReader look-ahead - #19399

Merged
JackieTien97 merged 8 commits into
apache:masterfrom
samyak-jain-dev:fix_aligned_priority_merge_reader
Nov 28, 2026
Merged

JackieTien97 merged 8 commits into
apache:masterfrom
samyak-jain-dev:fix_aligned_priority_merge_reader

Conversation

@samyak-jain-dev

@samyak-jain-dev samyak-jain-dev commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #19392

Description

Root Cause

In PriorityMergeReader.updateHeap(TimeValuePair ret, TimeValuePair topNext), when advancing a lower-priority reader e that shared topTime, the look-ahead optimization checked e.currTime() == topNextTime and immediately called fillNullValue(topNext, e.getTimeValuePair()) before skipping e.

For aligned time series (AlignedPriorityMergeReader and AlignedDescPriorityMergeReader), topNext can contain null field slots that must be filled in strict descending priority order across all readers present at topNextTime. Eagerly merging an older reader e into topNext while processing topTime populates null fields with stale values before an intermediate-priority reader starting (or ending, for descending scans) at topNextTime is visited. Because AlignedPriorityMergeReader.fillNullValueInAligned() only fills null slots, the fresher middle-priority field value is silently discarded.

Trigger Scenario (Before vs. After)

With three separate aligned sources for device d1 (fields x, y):

  • Reader 1 (oldest, priority 1): (10: null, 100), (20: null, 200)
  • Reader 2 (middle, priority 2): (20: null, 220)
  • Reader 3 (newest, priority 3): (10: 110, null), (20: 120, null)
Query / Scan Before After
Point lookup at time = 20 (20, 120, 220) (20, 120, 220)
Ascending scan (ORDER BY time) (10, 110, 100), (20, 120, 200) (stale y) (10, 110, 100), (20, 120, 220)
Filter WHERE x = 120 AND y = 220 0 rows (matching row filtered out) (20, 120, 220)

The same bug symmetrically affects descending aligned scans (AlignedDescPriorityMergeReader) when processing t=20 and looking ahead to t=10.

Fix

  • Introduced AlignedPointReader (extending IPointReader) with boolean isLastRowComplete() so aligned row builders record row completeness while constructing each TsVector — avoiding any extra vector scan on wide rows:
    • Added TsBlockAlignedRowPointReader and wired it into AlignedSeriesScanUtil.getPointReader(TsBlock) and AlignedReadOnlyMemChunk.getPointReader().
    • Implemented AlignedPointReader in AlignedTVList.AlignedTVListIterator and MultiAlignedTVListIterator to track completeness while assembling each vector in nextTimeValuePair().
  • Cached currentRowComplete on Element whenever nextTimeValuePair() is fetched (falling back conservatively to false for non-AlignedPointReader implementations with zero vector scanning).
  • Updated PriorityMergeReader, AlignedPriorityMergeReader, and AlignedDescPriorityMergeReader:
    • Removed the premature fillNullValue(topNext, ...) call from the look-ahead path.
    • Replaced per-row vector scanning with an O(1) isRowComplete(Element) hook (always true for scalar readers; element.isCurrentRowComplete() for aligned readers):
      • When topNext is complete, the fast look-ahead skip optimization is preserved in O(1).
      • When topNext is incomplete (or comes from a non-tracking IPointReader), lower-priority readers stay in the heap with zero extra scan and merge in strict descending priority order when topNext is popped.
      • When topNext == null, canSkipNext is false, so scalar points at Long.MAX_VALUE are never skipped.
      • When ret is already complete (either from isRowComplete(top) or once fillNullValue returns true), updateHeap short-circuits remaining column scans across overlapping readers.
    • Consolidated duplicate element memory-release and close logic into releaseAndCloseElement(Element).

Verification

  • Added regression unit tests in AlignedPriorityMergeReaderTest:
    • testAscScanMergesMiddlePriorityReaderAtNextTimestamp (reproduces [Bug] Table model: ascending scan returns a stale field value and a matching row is filtered out #19392)
    • testDescScanMergesMiddlePriorityReaderAtNextTimestamp (symmetric descending aligned scan case)
    • testAscScanPreservesOlderColumnsWhileMiddleOverridesOverlappingColumn (verifies 3-column partial merges across 3 priorities)
    • testSkipOlderReaderOnlyWhenNextAlignedRowIsComplete (verifies TsBlockAlignedRowPointReader O(1) complete-row early skip in both asc/desc scans, incomplete-row retention, fillNullValueInAligned completion reporting, and conservative no-scan fallback for non-AlignedPointReader sources)
  • Added regression unit test and row-count assertions in PriorityMergeReaderTest:
    • testPointAtLongMaxValueNotSkippedWhenTopEnds (verifies points at Long.MAX_VALUE are preserved when a higher-priority reader ends)
    • Added missing row-count assertions in testAsc and testDesc
  • Added end-to-end Table-model SQL integration test in IoTDBAlignedSeriesQueryTableIT#partialUpdateMergeAcrossMultipleFlushesTest:
  • Local verification:
    • ./mvnw spotless:apply -pl iotdb-core/datanode and ./mvnw spotless:apply -pl integration-test -P with-integration-tests (passed)
    • ./mvnw test -pl iotdb-core/datanode -am -Dtest="AlignedPriorityMergeReaderTest,PriorityMergeReaderTest,*AlignedTVList*Test,*SeriesScan*Test" -Dsurefire.failIfNoSpecifiedTests=false (134/134 datanode tests passed)
    • ./mvnw test-compile -pl iotdb-core/datanode -am -P with-zh-locale -DskipTests (passed)
    • python3 .github/scripts/check-it-selection.py (passed)
    • ./mvnw verify -DskipUTs -Dit.test=IoTDBAlignedSeriesQueryTableIT#partialUpdateMergeAcrossMultipleFlushesTest -DfailIfNoTests=false -Dfailsafe.failIfNoSpecifiedTests=false -pl integration-test -am -P TableSimpleIT -P with-integration-tests (1/1 passed in TableSimpleIT / 1C1D; Apache RAT 0 unapproved; 1C3D runs in CI)

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues were identified for the changes preserving field priority when merging partial aligned rows.

No open issues 🎉

What changed in this PR

Fixes #19392 by preserving field priority when merging partial aligned rows, preventing stale values and incorrectly filtered results in ascending and descending scans.

Changes:

  • Defers look-ahead skipping for incomplete aligned rows while retaining the optimization for complete rows.
  • Preserves scalar points at Long.MAX_VALUE, short-circuits completed field merges, and consolidates reader cleanup.
  • Adds unit and SQL regression coverage for priority ordering, partial updates, scan direction, and flush boundaries.
File Description
iotdb-core/​datanode/​src/​test/​java/​org/​apache/​iotdb/​db/​storageengine/​dataregion/​read/​reader/​common/​PriorityMergeReaderTest.java Tests maximum timestamps and strengthens row-count assertions.
iotdb-core/​datanode/​src/​test/​java/​org/​apache/​iotdb/​db/​storageengine/​dataregion/​read/​reader/​common/​AlignedPriorityMergeReaderTest.java Tests partial-row priority merging and complete-row skipping.
iotdb-core/​datanode/​src/​main/​java/​org/​apache/​iotdb/​db/​storageengine/​dataregion/​read/​reader/​common/​PriorityMergeReader.java Guards look-ahead skipping and consolidates reader cleanup.
iotdb-core/​datanode/​src/​main/​java/​org/​apache/​iotdb/​db/​storageengine/​dataregion/​read/​reader/​common/​AlignedPriorityMergeReader.java Checks row completeness and reports when field merging is complete.
iotdb-core/​datanode/​src/​main/​java/​org/​apache/​iotdb/​db/​storageengine/​dataregion/​read/​reader/​common/​AlignedDescPriorityMergeReader.java Applies the same completeness checks to descending scans.
integration-test/​src/​test/​java/​org/​apache/​iotdb/​relational/​it/​query/​old/​aligned/​IoTDBAlignedSeriesQueryTableIT.java Verifies SQL results and filters across partial updates and flushes.

Review effort: Balanced

Comment on lines +47 to +58
static boolean hasNoNullFields(TimeValuePair pair) {
TsPrimitiveType value = pair.getValue();
if (value == null) {
return false;
}
for (TsPrimitiveType field : value.getVector()) {
if (field == null || field.getValue() == null) {
return false;
}
}
return true;
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have a performance concern here for wide rows. If only the last field is null, hasNoNullFields() scans the entire vector just to determine that the lower-priority point must stay in the heap. fillNullValueInAligned() then scans the row again when the points are merged. In an in-memory microbenchmark with 256 fields and two readers whose timestamps fully overlapped, this case took about 210 ns per output row, compared with 130 ns with look-ahead skipping disabled. Could we track whether the row is complete while building the vector and check that flag here? That would preserve the fast path for complete rows while avoiding the extra scan.

@samyak-jain-dev samyak-jain-dev Nov 26, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes total sense, thanks for benchmarking that! I removed hasNoNullFields() in 304bf2c and instead tracked completeness while building each row via a small AlignedPointReader interface across the TsBlock and AlignedTVList iterators (since TsVector is in tsfile). PriorityMergeReader now just checks that cached boolean in O(1), and all unit tests + the table IT pass locally. Ready for another look whenever you get a chance!

@ColinLeeo

Copy link
Copy Markdown
Collaborator

Could we give partialUpdateMergeAcrossMultipleFlushesTest its own database and use FLUSH <database> there? TableUtils.insertData() leaves the last batch for table0 in memory. The first plain FLUSH in the new test writes that batch to disk too, so any tests that run afterward lose coverage of reading table0 from both memory and disk.

@samyak-jain-dev

Copy link
Copy Markdown
Contributor Author

Could we give partialUpdateMergeAcrossMultipleFlushesTest its own database and use FLUSH <database> there? TableUtils.insertData() leaves the last batch for table0 in memory. The first plain FLUSH in the new test writes that batch to disk too, so any tests that run afterward lose coverage of reading table0 from both memory and disk.

Good catch, I hadn't noticed table0 keeps its last batch in memory! Updated partialUpdateMergeAcrossMultipleFlushesTest in 0e55257 to create its own merge_lookahead_db database, flush with FLUSH merge_lookahead_db, and drop it in finally. Re-ran the IT locally and it passes.

@JackieTien97 JackieTien97 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the fix and the follow-up to track row completeness while building vectors! The core correctness fix and aligned wide-row performance look solid, and the isolated table IT is clean.

Requesting changes mainly to avoid a 10%–17% performance regression on the non-aligned (scalar) PriorityMergeReader hot path (measured locally on JDK 21 with polymorphic call sites) and to add a small null-guard for topNext — see inline comments below.


public void next() throws IOException {
timeValuePair = reader.nextTimeValuePair();
currentRowComplete = isReaderRowComplete(reader);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

reader is final, so calling isReaderRowComplete(reader) (which performs reader instanceof AlignedPointReader) inside Element.next() adds per-point overhead on every advance—including for non-aligned (scalar) PriorityMergeReader / DescPriorityMergeReader (which never read currentRowComplete), and for skipped lower-priority elements in updateHeap().

Also note setTimeValuePair() does not update currentRowComplete, which could leave it stale if ever called with a different pair.

Could we resolve AlignedPointReader once in the constructor and query it lazily in isCurrentRowComplete(), leaving Element.next() untouched?

private final AlignedPointReader alignedReader;

public Element(IPointReader reader, TimeValuePair timeValuePair, MergeReaderPriority priority) {
  this.reader = reader;
  this.alignedReader = reader instanceof AlignedPointReader ? (AlignedPointReader) reader : null;
  this.timeValuePair = timeValuePair;
  this.priority = priority;
}

public boolean isCurrentRowComplete() {
  return alignedReader != null && alignedReader.isLastRowComplete();
}

public void next() throws IOException {
  timeValuePair = reader.nextTimeValuePair();
}

In PriorityMergeReader, the last call on an element's reader before isRowComplete(top) is always nextTimeValuePair(), and hasNextTimeValuePair() does not mutate isLastRowComplete() by contract, so querying alignedReader.isLastRowComplete() on demand is equivalent while incurring zero overhead in next().

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks a lot for the detailed review and benchmarks! Addressed all four points in 9f21baf:

Resolved alignedReader once in Element's constructor and queried isLastRowComplete() lazily, leaving Element.next() untouched.
Added the hasOverlap fast path and topNext != null guard in PriorityMergeReader (plus a unit test for a null second nextTimeValuePair()).
Short-circuited the TsBinary check with if (complete && ...) in TsBlockAlignedRowPointReader, AlignedTVListIterator, and MultiAlignedTVListIterator.
Added direct unit tests for isLastRowComplete() across AlignedTVListIterator, OrderedMultiAlignedTVListIterator, and MergeSortMultiAlignedTVListIterator (complete rows, null TEXT values, deleted columns, and ensuring hasNextTimeValuePair() doesn't mutate it).

Comment on lines +90 to +100
Element top = heap.poll();
TimeValuePair ret = top.getTimeValuePair();
boolean retComplete = isRowComplete(top);
TimeValuePair topNext = null;
boolean canSkipNext = false;
if (top.hasNext()) {
top.next();
topNext = top.currPair();
canSkipNext = isRowComplete(top);
}
updateHeap(ret, topNext);
updateHeap(ret, topNext, retComplete, canSkipNext);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two points here:

  1. Scalar / non-overlapping hot-path regression: isRowComplete(top) is currently invoked twice via polymorphic dispatch on every output row even when there is no same-timestamp overlap (heap.isEmpty() || heap.peek().currTime() != ret.getTimestamp()). Combined with Element.next() doing instanceof AlignedPointReader per point, local microbenchmarks (JDK 21, 16k rows, megamorphic IPointReader / PriorityMergeReader call sites) show a reproducible 10%–17% regression on non-aligned scalar scans (100% overlap: ~39 -> ~44 ns/row; interleaved non-overlap: ~23.1 -> ~25.5 ns/row; 1-reader drain: ~19.3 -> ~22.5 ns/row).
  2. Null safety for topNext: If top.hasNext() returns true and an IPointReader returns null from nextTimeValuePair(), canSkipNext = isRowComplete(top) evaluates to true for scalar PriorityMergeReader, causing topNext.getTimestamp() in updateHeap to throw an NPE (whereas both the previous code and line 101 if (topNext != null) guard against topNext == null).

Both can be addressed cleanly by checking hasOverlap first and guarding topNext != null:

Element top = heap.poll();
TimeValuePair ret = top.getTimeValuePair();
boolean hasOverlap = !heap.isEmpty() && heap.peek().currTime() == ret.getTimestamp();
boolean retComplete = hasOverlap && isRowComplete(top);
TimeValuePair topNext = null;
boolean canSkipNext = false;
if (top.hasNext()) {
  top.next();
  topNext = top.currPair();
  if (hasOverlap && topNext != null) {
    canSkipNext = isRowComplete(top);
  }
}
if (hasOverlap) {
  updateHeap(ret, topNext, retComplete, canSkipNext);
}

Together with caching alignedReader in Element, this completely eliminates the scalar regression in the benchmark while keeping all aligned gains.

} else {
TsPrimitiveType val = col.getTsPrimitiveType(rowIndex);
vector[i] = val;
if (val == null || (val instanceof TsBinary && val.getBinary() == null)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor nit: guarding with if (complete && (val == null || (val instanceof TsBinary && val.getBinary() == null))) (same in AlignedTVListIterator and MultiAlignedTVListIterator) avoids repeating the instanceof TsBinary check for the remaining columns once a row already has a null slot.


@Test
public void testSkipOlderReaderOnlyWhenNextAlignedRowIsComplete() throws IOException {
assertFalse(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we also add direct unit tests covering isLastRowComplete() on AlignedTVListIterator and MultiAlignedTVListIterator (OrderedMultiAlignedTVListIterator and MergeSortMultiAlignedTVListIterator) for complete vs. incomplete rows (including null TsBinary / deleted column cases)? Right now unit tests only exercise TsBlockAlignedRowPointReader and the non-AlignedPointReader fallback directly.

@ColinLeeo

ColinLeeo commented Nov 27, 2026 •

Copy link
Copy Markdown
Collaborator

1. Row completeness in TsFile’s TsBlock iterator (non-blocking)

Consider exposing whether the last row returned by getTsBlockAlignedRowIterator() contained any nulls. The iterator already checks each selected column while building the row. Recording the result there would allow IoTDB to reuse the existing iterator and keep the row-building logic in one place.

2. Consistent reads across external TsFiles (non-blocking)

I suggest tracking file precedence for read_tsfile in a separate issue. When two external files have equal merge priority and contain conflicting values for the same device, timestamp, and field, the tie-breaking rule is undefined. In a reader-level test with the same files and scan range, reading x alone returned 120, while reading x, y, z returned 999 for x at the same timestamp. Changing the scan start could also change the result before this PR.

The follow-up should define file precedence for both explicit file lists and directory inputs. Regression tests should verify that selecting additional columns or switching between a point lookup and a range scan preserves the value of the same field at the same timestamp.

@JackieTien97
JackieTien97 merged commit 96a0c6d into apache:master Nov 28, 2026
38 of 39 checks passed
@JackieTien97

Copy link
Copy Markdown
Contributor

plz cp to dev/1.3 branch @samyak-jain-dev

@samyak-jain-dev

samyak-jain-dev commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor Author

plz cp to dev/1.3 branch [@samyak-jain-dev](https://github.com/samyak-jain-dev

Done! Opened #19440 for dev/1.3 (adapted the IT to Tree model since dev/1.3 doesn't have the table model.

ColinLeeo pushed a commit that referenced this pull request Nov 29, 2026
…k-ahead (#19399) (#19440)

Co-authored-by: samyak <284592766+ritujain8638-source@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Table model: ascending scan returns a stale field value and a matching row is filtered out

4 participants